package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.ClienteDAO;
import model.Projeto;

/**
 * Servlet implementation class ClienteProjetoServlet
 */
@WebServlet("/ClienteProjetoServlet")
public class ClienteProjetoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ClienteProjetoServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request, response);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			NumberFormatException, SQLException {

		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String cnpj = request.getParameter("cnpj");
		ClienteDAO dao = new ClienteDAO();
		ArrayList<Projeto> list = dao
				.getProjetosCliente(cnpj);
		try {
			out.printf("<option value='%1s' selected>%2s</option>", "0", "-- Selecione --");
			for (Projeto projeto : list) {
				out.printf("<option value='%1s'>%2s</option>",
						projeto.getReferencia(), projeto.getReferencia()
								+ "-" + projeto.getTitulo());
			}
		} finally {
			out.close();
		}
	}
}
